# -*- coding: utf-8 -*-
# @Time: 2023/4/18 0:09
# @File: uploadfiles.py
# @Desc:封装上传文件

import os
from hashlib import md5
from time import time

"""
def avatar_upload():
    form = UploadAvatarForm(request.files)
    if form.validate():
        image = form.image.data
        filename = image.filename
        _, ext = os.path.splitext(filename)  # 拆分文件名
        filename = md5((g.user.id + str(time.time())).encode("utf8")).hexdigest() + ext  # 重命名文件名
        image_path = os.path.join(current_app.config["AVATARS_SAVE_PATH"], filename)  # 获取图片保存路径
        image.save(image_path)
        g.user.avatar = filename
        db.session.commit()
        return restful.success(data={"avatar": filename})
    else:
        return restful.params_error(message=form.message[0])

"""


def upload_files(file, uid, path):
    """
    上传文件
    :param file: 文件名
    :param uid: 用户ID
    :param path: config中保存文件的path
    :return:
    """
    filename = file.filename
    # 拆分文件名
    _, ext = os.path.splitext(filename)
    # 使用用户ID和时间戳组合通过md5加密重命名文件名
    filename = md5((uid + str(time.time())).encode("utf8")).hexdigest() + ext
    file_path = os.path.join(path, filename)
    return file_path
